package com.web.dao.chapter;

import com.web.bean.chapter.Chapter;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @autor Chen
 * @create 2021--25-13:05
 * @desc
 */
public class ChapterDaoImpl implements ChapterDao {
    private Connection connection = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;
    public ChapterDaoImpl(Connection connection) {
        this.connection = connection;
    }

    @Override
    public Chapter selectChapterById(String id) throws Exception {
        Chapter chapter = new Chapter();
        String sql = "select * from wn_chapter where chapterid=?";
        pst = connection.prepareStatement(sql);
        pst.setString(1,id);
        rs = pst.executeQuery();
        while (rs.next()){
            chapter = getChapter(rs);
        }
        return chapter;
    }

    private Chapter getChapter(ResultSet rs) throws SQLException {
        Chapter chapter = new Chapter();
        if (rs!=null){
            chapter.setNid(rs.getString(1));
            chapter.setChapterid(rs.getString(2));
            chapter.setCname(rs.getString(3));
            chapter.setCsrc(rs.getString(4));
            return chapter;
        }
        return null;
    }

    @Override
    public List<Chapter> selectChapters(String nid) throws Exception {
        List<Chapter> chapters = new ArrayList<>();
        String sql = "select * from wn_chapter where nid=?";
        pst = connection.prepareStatement(sql);
        pst.setString(1,nid);
        rs = pst.executeQuery();
        while (rs.next()){
            Chapter chapter = getChapter(rs);
            chapters.add(chapter);
        }
        return chapters;
    }

    @Override
    public void addChapter(Chapter chapter) throws Exception {
        String sql = "insert into wn_chapter value(?,?,?,?)";
        pst = connection.prepareStatement(sql);
        pst.setString(1,chapter.getNid());
        pst.setString(2,chapter.getChapterid());
        pst.setString(3,chapter.getCname());
        pst.setString(4,chapter.getCsrc());
        pst.executeUpdate();
    }
    @Override
    public void addChapters(List<Chapter> chapters) throws Exception {

    }

    @Override
    public void updateChapter(Chapter chapter) throws Exception {
        String sql = "update wn_chapter set cname=? , csrc=? where chapterid=?";
        pst = connection.prepareStatement(sql);
        pst.setString(1,chapter.getCname());
        pst.setString(2,chapter.getCsrc());
        pst.setString(3,chapter.getChapterid());
        pst.executeUpdate();
    }

    @Override
    public void deleteChapterById(String id) throws Exception {
        String sql = "delete from wn_chapter where chapterid=?";
        pst = connection.prepareStatement(sql);
        pst.setString(1,id);
        pst.executeUpdate();
    }
}
